<template>
  <transition
      appear
      @before-appear="beforeEnter"
      @after-appear="afterEnter"
      @after-leave="handleAnimationEnd"
      v-for="(item,index) in showBall"
      :key="index"
  >
    <!-- 小球 -->
    <div :style="ballStyle" class="Ball" v-if="item">
      <el-image :src="src"></el-image>
    </div>
  </transition>
</template>

<script lang="ts" setup>
import { ref, watch} from "vue";
import { ElImage } from 'element-plus'
const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  position: {
    type: Object,
    default: () => {}
  },
  elPosition: {
    type: Object,
    default: () => {}
  },
  showBall: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(['transEnd'])
const elLeft = ref(0) //记录当前点击加入购物车的小商品距离网页左边的距离
const elTop = ref(0)//记录当前点击加入购物车的小商品距离网页顶部的距离

const ballStyle = ref({
  left: elLeft.value,
  top: elTop.value
})

watch(
    () => props.elPosition,
    (newVal: any) => {
      elLeft.value = newVal.left
      elTop.value = newVal.top
    },
    {
      deep: true
    }
)

// 动画开始了
const beforeEnter = (el: any)=>{
  el.style.transform = `translate3d(${elLeft.value - 55}px,${elTop.value - 80}px,0)`
}
// 动画结束了
const afterEnter = (el: any) => {
  //购物车到网页左边和顶部的距离
  const { left,top } = props.position
  //设置小球移动的位移目标点
  el.style.transform = `translate3d(${left - 10}px,${top + 30}px,0)`
  //增加贝塞尔曲线，让移动路径为曲线
  el.style.transition = 'transform .55s cubic-bezier(0.3,-0.25,0.7,-0.15)'
  el.style.transition = 'transform .55s linear'
}

const handleAnimationEnd = ()=>{
  setTimeout(() => {
    emits('transEnd', props.showBall.map((item: any) => false))
  }, 600)
  //调用将商品加入购物车的方法，动画结束后才将商品数据添加到购物车
}
</script>

<style scoped lang="scss">
.Ball{
  position: fixed;
  width: 30px;
  height: 30px;
  border-radius: 15px;
  ::v-deep .el-image {
    animation: 1s ballScale ease-in-out;
    >img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }
  }
}
@keyframes ballScale {
  0%{
    transform: scale(1);
  }
  25%{
    transform: scale(0.8);
  }
  50%{
    transform: scale(0.6);
  }
  75%{
    transform: scale(0.4);
  }
  100%{
    transform: scale(0.1);
  }
}
</style>